/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.saber.certificacao.beansjsf.login;

import br.com.saber.certificacao.beansjsf.interfacebean.BeanJSFInterface;
import br.com.saber.certificacao.ejbs.stateless.interfaces.RolesBeanLocal;
import br.com.saber.certificacao.ejbs.stateless.interfaces.UsuarioBeanLocal;
import br.com.saber.certificacao.enums.Papeis;
import br.com.saber.certificacao.modelos.Roles;
import br.com.saber.certificacao.modelos.Usuario;
import br.com.saber.certificacao.modelos.validadores.exceptions.generica.ValidacaoExcecao;
import br.com.saber.certificacao.utils.UtilMetodos;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author gbvbahia
 */
@ManagedBean(name = "userAcessoManager")
@ViewScoped
public class UserAcessoManager implements BeanJSFInterface {

    @EJB
    private RolesBeanLocal rolesBean;
    @EJB
    private UsuarioBeanLocal usuarioBean;
    private String email2;
    private String passReset;
    private Usuario usuarioCadastro;
    private String actionEvent;
    @ManagedProperty("#{fluxoExibicaoLogin}")
    private FluxoExibicao fluxoExibicao;

    /** Creates a new instance of UserManager */
    public UserAcessoManager() {
    }

    //====================
    // Iniciadores
    //====================
    @Override
    @PostConstruct
    public void init() {
        clean();
        Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "UserAcessoManager.init() executado!");
    }

    @Override
    @PreDestroy
    public void end() {
        Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "UserAcessoManager.end() executado!");
    }

    //====================
    //Métodos de Negócio
    //====================
    public void salvarUsuario(ActionEvent event) {
        try {
            if (!usuarioCadastro.getEmail().equals(email2)) {
                UtilMetodos.messageFactoringFull("usuarioCadastradoEmailNOk", FacesMessage.SEVERITY_WARN, FacesContext.getCurrentInstance());
                return;
            }
            usuarioBean.salvarUsuario(usuarioCadastro, UtilMetodos.getURL(FacesContext.getCurrentInstance()));
            clean();
            UtilMetodos.messageFactoringFull("usuarioCadastradoOk", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
            UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso2", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
            UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso3", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
            UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso4", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
            fluxoExibicao.exibirLogin();
        } catch (ValidacaoExcecao e) {
            if (!StringUtils.isBlank(e.getAtributoName())) {
                UtilMetodos.messageFactoringFull(UtilMetodos.getResourceBundle(e.getMessage(), FacesContext.getCurrentInstance()), null, e.getAtributoName(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
            } else {
                UtilMetodos.messageFactoringFull(e.getMessage(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
            }
        }
    }

    public void resetarSenha() {
        Usuario userToResetPass = usuarioBean.buscarUsuarioEmail(this.passReset);
        if (userToResetPass == null) {
            UtilMetodos.messageFactoringFull("usuarioSenhaEmailLostError", FacesMessage.SEVERITY_WARN, FacesContext.getCurrentInstance());
            return;
        } else {
            try {
                userToResetPass.setSenha(null);
                usuarioBean.salvarUsuario(userToResetPass, UtilMetodos.getURL(FacesContext.getCurrentInstance()));
                clean();
                UtilMetodos.messageFactoringFull("usuarioCadastradoOk", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
                UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso2", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
                UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso3", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
                UtilMetodos.messageFactoringFull("usuarioSenhaEmailAviso4", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
                fluxoExibicao.exibirLogin();
            } catch (ValidacaoExcecao e) {
                if (!StringUtils.isBlank(e.getAtributoName())) {
                    UtilMetodos.messageFactoringFull(UtilMetodos.getResourceBundle(e.getMessage(), FacesContext.getCurrentInstance()), null, e.getAtributoName(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
                } else {
                    UtilMetodos.messageFactoringFull(e.getMessage(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
                }
            }
        }
    }

    public void clean() {
        this.usuarioCadastro = new Usuario();
        Roles userRole = rolesBean.buscarRolePorPapel(Papeis.ALUNO);
        usuarioCadastro.getRoles().add(userRole);
        this.email2 = "";
    }

    //====================
    //Table Actions
    //====================
    //====================
    //SelectItem
    //====================
    //=========================
    //Getters AND Setters
    //=========================
    public Usuario getUsuarioCadastro() {
        return usuarioCadastro;
    }

    public void setUsuarioCadastro(Usuario usuarioCadastro) {
        this.usuarioCadastro = usuarioCadastro;
    }

    public List<Roles> getListRoles() {
        return new ArrayList<Roles>(usuarioCadastro.getRoles());
    }

    public void setListRoles(List<Roles> listRoles) {
        usuarioCadastro.setRoles(new TreeSet<Roles>(listRoles));
    }

    public String getActionEvent() {
        return actionEvent;
    }

    public FluxoExibicao getFluxoExibicao() {
        return fluxoExibicao;
    }

    public void setFluxoExibicao(FluxoExibicao fluxoExibicao) {
        this.fluxoExibicao = fluxoExibicao;
    }

    public String getEmail2() {
        return email2;
    }

    public void setEmail2(String email2) {
        this.email2 = email2;
    }

    public String getPassReset() {
        return passReset;
    }

    public void setPassReset(String passReset) {
        this.passReset = passReset;
    }
}
